//
// Created by swe_dev on 25-2-15.
//

#ifndef FISH_FEEDER_HPP
#define FISH_FEEDER_HPP

#include "task.hpp"
#include "stm32f1xx_hal.h"

#define STATE_FEEDING   1
#define STATE_FEED_DONE 2

class FishFeeder : public Task {
public:
    FishFeeder() {
        period_ms = 1U;
    }

    void period_task() override {
        if (state == STATE_FEEDING) {
            motor_shake(50, 1);
            auto position = HAL_GPIO_ReadPin(position_gpio_bank, position_gpio_pin);
            if (position == 1) {
                ++feed_count;
                if (feed_count >= 1) {
                    feed_count = 0;
                    state = STATE_FEED_DONE;
                } else {
                    task_yield(500);
                    motor_shake(250, 0);
                }
            }
        }

        auto feed_key = HAL_GPIO_ReadPin(key_gpio_bank, key_gpio_pin);
        if (feed_key == 0) {
            state = STATE_FEEDING;
            motor_shake(500, 1);
        }
    }

protected:
    void motor_shake(uint32_t action_time, uint32_t stop_time) {
        HAL_GPIO_WritePin(motor_gpio_bank, motor_gpio_pin, GPIO_PIN_SET);
        task_yield(action_time);
        HAL_GPIO_WritePin(motor_gpio_bank, motor_gpio_pin, GPIO_PIN_RESET);
        task_yield(stop_time);
    }

protected:
    GPIO_TypeDef* motor_gpio_bank{GPIOB};
    uint16_t motor_gpio_pin{GPIO_PIN_0};
    GPIO_TypeDef* position_gpio_bank{GPIOB};
    uint16_t position_gpio_pin{GPIO_PIN_12};
    GPIO_TypeDef* key_gpio_bank{GPIOB};
    uint16_t key_gpio_pin{GPIO_PIN_14};
    uint8_t state{STATE_FEED_DONE};
    uint32_t feed_count{0U};
};

#endif //FISH_FEEDER_HPP
